/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[欢迎加盟知启蒙，一起邂逅框架梦]
 * 
 * https://www.zhiqim.com/gitcan/zhiqim/zhiqim_account.htm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zhiqim.account;

import org.zhiqim.account.presenter.UserPassportPresenter;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.core.Interceptor;
import org.zhiqim.kernel.util.Urls;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.manager.dao.ZmrParamDao;

/**
 * 登录检查
 *
 * @version v1.0.0 @author zouzhigang 2017-6-28 新建与整理
 */
public class ZacInterceptor implements Interceptor, ZacConstants
{
    @Override
    public void intercept(HttpRequest request) throws Exception
    {
        if(request.hasSessionUser(ZacSessionUser.class))
        {
            request.setSessionUserClass(ZacSessionUser.class);
            return;
        }
        
        String isRemember = request.getCookie("isRemember");
        String userAccount = request.getCookie("userAccount");
        String userPass = request.getCookie("userPass");
        if (Validates.isNotEmpty(isRemember) && Validates.isNotEmpty(userAccount) && Validates.isNotEmpty(userPass))
        {//勾选了自动登录，session结束后自动登录
            request.setParameterOnCNT("isRemember", isRemember);
            request.setParameterOnCNT("userAccount", userAccount);
            request.setParameterOnCNT("userPass", userPass);
            request.setParameterOnCNT("isAuto", "on");
            UserPassportPresenter.login(request);
            return;
        }
        
        if (!request.isMicroMessenger() || !hasMicroMessengerConfig())
        {//不是微信公众号或未配置微信公众号参数
            request.setRedirect("/login.htm?to="+Urls.encodeUTF8(request.getRequestURI()));
            return;
        }
        
        request.setRedirect("/connect/wxmp" + request.getRequestURI());
    }
    
    /** 是否配置微信公众号参数 */
    private boolean hasMicroMessengerConfig() throws Exception
    {
        return Validates.isNotEmptyBlank(ZmrParamDao.getString(ZAC_NAME, WXMP_APP_ID)) &&
                Validates.isNotEmptyBlank(ZmrParamDao.getString(ZAC_NAME, WXMP_APP_SECRET)) &&
                Validates.isNotEmptyBlank(ZmrParamDao.getString(ZAC_NAME, WXMP_CALLBACK));
    }
}
